import Workspace from "@/models/workspace";
import RenameModals from "@/components/Modals/RenameModals";
import RemoveModals from "@/components/Modals/RemoveModals";
import paths from "@/utils/paths";
import { message } from "antd";
import { useEffect, useRef, useState } from "react";
import { useParams } from "react-router-dom";
import DotActive from "@/media/sidebar/dot-active.png";
const THREAD_CALLOUT_DETAIL_WIDTH = 26;
export default function ThreadItem({
  idx,
  activeIdx,
  isActive,
  workspace,
  thread,
  onRemove,
  toggleMarkForDeletion,
  hasNext,
  ctrlPressed = false,
}) {
  const { slug, threadSlug = null } = useParams();
  const optionsContainer = useRef(null);
  const [showOptions, setShowOptions] = useState(false);
  const linkTo = !thread.slug
    ? paths.workspace.chat(slug)
    : paths.workspace.thread(slug, thread.slug);

  return (
    // 会话
    <div
      className="w-full relative flex h-[40px] chat-list items-center border-none rounded-lg"
      role="listitem"
    >
      {/* Curved line Element and leader if required */}
      {/* <div
        style={{ width: THREAD_CALLOUT_DETAIL_WIDTH / 2 }}
        className={`${
          isActive
            ? "border-l-2 border-b-2 border-white light:border-theme-sidebar-border z-[2]"
            : "border-l border-b border-[#6F6F71] light:border-theme-sidebar-border z-[1]"
        } h-[50%] absolute top-0 left-3 rounded-bl-lg`}
      ></div> */}
      {/* Downstroke border for next item */}
      {/* {hasNext && (
        <div
          style={{ width: THREAD_CALLOUT_DETAIL_WIDTH / 2 }}
          className={`${
            idx <= activeIdx && !isActive
              ? "border-l-2 border-white light:border-theme-sidebar-border z-[2]"
              : "border-l border-[#6F6F71] light:border-theme-sidebar-border z-[1]"
          } h-[100%] absolute top-0 left-3`}
        ></div>
      )} */}

      {/* Curved line inline placeholder for spacing - not visible */}
      {/* <div
        style={{ width: THREAD_CALLOUT_DETAIL_WIDTH + 8 }}
        className="h-full"
      /> */}
      <div
        className={`flex w-full items-center justify-between group relative bg-theme-sidebar-item-default h-full p-[10px]`}
      >
        {/* 当前选中对话，不能删除 */}
        {thread.deleted ? (
          <div className="w-full flex justify-between">
            <div className="w-full pl-2 py-1">
              <p
                className={`text-left text-sm text-slate-400/50 light:text-slate-500 italic`}
              >
                deleted thread
              </p>
            </div>
            {ctrlPressed && (
              <button
                type="button"
                className="border-none"
                onClick={() => toggleMarkForDeletion(thread.id)}
              >
                <ArrowCounterClockwise
                  className="text-zinc-300 hover:text-white light:text-theme-text-secondary hover:light:text-theme-text-primary"
                  size={18}
                />
              </button>
            )}
          </div>
        ) : (
          // 默认对话，不允许删除
          <a
            href={
              window.location.pathname === linkTo || ctrlPressed ? "#" : linkTo
            }
            className="w-full overflow-hidden"
            aria-current={isActive ? "page" : ""}
          >
            <p
              className={`text-left text-sm truncate max-w-[150px] ${
                isActive ? "font-medium text-white" : "text-theme-text-primary"
              }`}
            >
              {thread.name}
            </p>
          </a>
        )}
        {/* 鼠标悬浮显示的三个点 */}
        {!!thread.slug && !thread.deleted && (
          <div ref={optionsContainer} className="flex items-center">
            {" "}
            {/* Added flex and items-center */}
            {ctrlPressed ? (
              <button
                type="button"
                className="border-none"
                onClick={() => toggleMarkForDeletion(thread.id)}
              >
                <X
                  className="text-zinc-300 light:text-theme-text-secondary hover:text-white hover:light:text-theme-text-primary"
                  weight="bold"
                  size={18}
                />
              </button>
            ) : (
              <div className="flex items-center w-fit group-hover:visible md:invisible gap-x-1">
                <button
                  type="button"
                  className="border-none"
                  onClick={(event) => {
                    event.stopPropagation();
                    setShowOptions(!showOptions);
                  }}
                  aria-label="Thread options"
                >
                  <img
                    src={DotActive}
                    alt="DotActive"
                    className="w-[16px] mx-[0px] hover-image group-hover:duration-200"
                  />
                </button>
              </div>
            )}
            {showOptions && (
              <OptionsMenu
                containerRef={optionsContainer}
                workspace={workspace}
                thread={thread}
                onRemove={onRemove}
                close={() => setShowOptions(false)}
                currentThreadSlug={threadSlug}
              />
            )}
          </div>
        )}
      </div>
    </div>
  );
}

function OptionsMenu({
  containerRef,
  workspace,
  thread,
  onRemove,
  close,
  currentThreadSlug,
}) {
  const menuRef = useRef(null);
  const [showModal, setShowModal] = useState(false);
  const [showRemoveModal, setShowRemoveModal] = useState(false);
  const hideModal = () => {
    setShowModal(false);
  };
  const hideRemoveModal = () => {
    setShowRemoveModal(false);
    close();
  };
  // Ref menu options
  const outsideClick = (e) => {
    if (!menuRef.current) return false;
    if (
      !menuRef.current?.contains(e.target) &&
      !containerRef.current?.contains(e.target)
    )
      close();
    return false;
  };

  const isEsc = (e) => {
    if (e.key === "Escape" || e.key === "Esc") close();
  };

  function cleanupListeners() {
    window.removeEventListener("click", outsideClick);
    window.removeEventListener("keyup", isEsc);
  }
  // end Ref menu options

  useEffect(() => {
    function setListeners() {
      if (!menuRef?.current || !containerRef.current) return false;
      window.document.addEventListener("click", outsideClick);
      window.document.addEventListener("keyup", isEsc);
    }

    setListeners();
    return cleanupListeners;
  }, [menuRef.current, containerRef.current]);

  // 重命名
  const renameThread = async (name) => {
    const res = await Workspace.threads.update(
      workspace.slug,
      thread.slug,
      name
    );
    if (res.message) {
      message.error(`Thread could not be updated! ${message}`);
      close();
      return;
    }
    thread.name = res.thread?.name;
    close();
  };

  // 删除
  const handleDelete = async () => {
    const success = await Workspace.threads.delete(workspace.slug, thread.slug);
    if (success) {
      message.success("Thread deleted successfully!");
      onRemove(thread.id);
      if (currentThreadSlug === thread.slug) {
        window.location.href = paths.workspace.chat(workspace.slug);
      }
      return;
    } else {
      message.error("Thread could not be deleted!");
      return;
    }
  };
  return (
    <>
      <div
        ref={menuRef}
        className="chat-tool w-[160px] absolute z-[20] top-[25px] right-[10px] bg-zinc-900 rounded-[8px] py-[4px]"
      >
        <button
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
            setShowModal(true);
          }}
          type="button"
          className="w-full rounded-[8px] flex items-center px-[12px] py-[8px] gap-x-2 text-slate-300 light:text-theme-text-primary"
        >
          <p className="text-sm tool-text">重命名</p>
        </button>
        <button
          onClick={(e) => {
            e.stopPropagation();
            e.preventDefault();
            setShowRemoveModal(true);
          }}
          type="button"
          className="w-full rounded-[8px] flex items-center pl-[12px] py-[8px] gap-x-2 hover:bg-red-500/20 text-slate-300 light:text-theme-text-primary hover:text-red-100"
        >
          <p className="text-sm tool-text">删除</p>
        </button>
      </div>
      {showModal && (
        <RenameModals
          hideModal={hideModal}
          handleModal={renameThread}
          placeholder="请输入对话名称"
        />
      )}
      {showRemoveModal && (
        <RemoveModals
          hideModal={hideRemoveModal}
          handleModal={handleDelete}
          title="确定删除此对话吗？"
          content="确定删除此对话吗？删除后将无法还原"
        />
      )}
    </>
  );
}
